package com.txzt.gaea.business.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.txzt.base.constant.RtnConstant;
import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.api.client.AdminUserRemoteService;
import com.txzt.gaea.business.project.domain.dto.ProjectContractDTO;
import com.txzt.gaea.business.project.domain.model.ProjectContract;
import com.txzt.gaea.business.project.domain.model.ProjectContractPayment;
import com.txzt.gaea.business.project.domain.model.ProjectInfo;
import com.txzt.gaea.business.project.domain.vo.ProjectContractVo;
import com.txzt.gaea.business.project.service.IProjectInfoService;
import com.txzt.gaea.business.project.service.ProjectContractService;
import com.txzt.gaea.common.base.service.impl.BaseServiceImpl;
import com.txzt.gaea.common.enums.IsDeleteEnum;
import com.txzt.gaea.common.enums.ProjectFileTypeEnum;
import com.txzt.gaea.common.page.PageInfoBT;
import com.txzt.gaea.dto.UserSingleDetailQueryDTO;
import com.txzt.gaea.provide.service.FileInfoService;
import com.txzt.gaea.provide.vo.FileInfoVo;
import lombok.extern.log4j.Log4j2;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Log4j2
@Service
public class ProjectContractServiceImpl extends BaseServiceImpl<ProjectContract> implements ProjectContractService {

    @Autowired
    private AdminUserRemoteService adminUserRemoteService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private IProjectInfoService iProjectInfoService;

    @Override
    public RtnInfo<PageInfoBT<ProjectContractVo>> pageList(ProjectContractDTO projectContractDTO){
        PageQuery<ProjectContractVo> pageQuery = new PageQuery<>(projectContractDTO.getOffset(),
                projectContractDTO.getLimit(), projectContractDTO);
        PageQuery<ProjectContractVo> result =
                this.sqlManager.pageQuery("projectContract.selectPageList", ProjectContractVo.class, pageQuery);
        //为空直接返回
        if (CollectionUtils.isEmpty(result.getList())) {
            return RtnInfo.success(new PageInfoBT<>(result));
        }
        result.getList().forEach(item -> {
            UserSingleDetailQueryDTO userSingleDetailQueryDTO = new UserSingleDetailQueryDTO();
            userSingleDetailQueryDTO.setUserId(item.getCreateBy());
            item.setCreateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
            userSingleDetailQueryDTO.setUserId(item.getUpdateBy());
            item.setUpdateName(adminUserRemoteService.singleDetailQuery(userSingleDetailQueryDTO).getData().getName());
        });
        PageInfoBT<ProjectContractVo> re = new PageInfoBT<>(result);
        rebuild(re);
        return RtnInfo.success(re);
    }

    private void rebuild(PageInfoBT<ProjectContractVo> re){
        List<ProjectContractVo> list = re.getRows();
        if(CollectionUtils.isEmpty(list)){
            re.setTotal(0);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(ProjectContract projectContract){
        int num = this.sqlManager.insert(projectContract,true);
        if (null == projectContract.getId()){
            return 0;
        }
        if (0 < projectContract.getPaymentList().size()) {
            for (ProjectContractPayment payment : projectContract.getPaymentList()) {
                payment.setBizId(projectContract.getId());
                this.sqlManager.insert(payment);
            }
        }
        //文件处理
        ProjectInfo projectInfo = iProjectInfoService.selectById(projectContract.getProjectId());
        if (null != projectContract.getFileContent()){
            List<FileInfoVo> fileList = JSON.parseArray(projectContract.getFileContent(), FileInfoVo.class);
            fileInfoService.fileChange(null,fileList,projectInfo.getProjectNo(), ProjectFileTypeEnum.PROJECT.getCode());
        }
        return num;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(ProjectContract projectContract){
        int num = this.sqlManager.updateTemplateById(projectContract);
        if (num == 0){
            return 0;
        }
        LambdaQuery<ProjectContractPayment> query = sqlManager.lambdaQuery(ProjectContractPayment.class);
        query.andEq(ProjectContractPayment::getBizId,projectContract.getId()).delete();
        if (0 < projectContract.getPaymentList().size()){
            for (ProjectContractPayment payment : projectContract.getPaymentList()){
                payment.setBizId(projectContract.getId());
                this.sqlManager.insert(payment);
            }
        }
        //文件归档处理
        ProjectContract oldOne = this.selectById(projectContract.getId());
        ProjectInfo projectInfo = iProjectInfoService.selectById(projectContract.getProjectId());
        if (null != oldOne.getFileContent() && null != projectContract.getFileContent()){
            List<FileInfoVo> oldList = JSON.parseArray(oldOne.getFileContent(), FileInfoVo.class);
            List<FileInfoVo> newList = JSON.parseArray(projectContract.getFileContent(), FileInfoVo.class);
            fileInfoService.fileChange(oldList,newList,projectInfo.getProjectNo(),ProjectFileTypeEnum.PROJECT.getCode());
        }else if (null != projectContract.getFileContent()){
            List<FileInfoVo> newList = JSON.parseArray(projectContract.getFileContent(), FileInfoVo.class);
            fileInfoService.fileChange(null,newList,projectInfo.getProjectNo(),ProjectFileTypeEnum.PROJECT.getCode());
        }
        return num;
    }

    @Override
    public boolean addCheck(ProjectContract projectContract){
        LambdaQuery<ProjectContract> query = sqlManager.lambdaQuery(ProjectContract.class);
        List<ProjectContract> orgList = query.andEq(ProjectContract::getContractName,projectContract.getContractName())
                .orEq(ProjectContract::getContractNo,projectContract.getContractNo())
                .andEq(ProjectContract::getIsDelete, IsDeleteEnum.NOTDELETE.getCode())
                .select();
        return 0 >= orgList.size();
    }

    @Override
    public boolean updateCheck(ProjectContract projectContract){
        LambdaQuery<ProjectContract> query = sqlManager.lambdaQuery(ProjectContract.class);
        List<ProjectContract> orgList = query.andEq(ProjectContract::getIsDelete,IsDeleteEnum.NOTDELETE.getCode())
                .andNotEq(ProjectContract::getId,projectContract.getId()).and(query.condition()
                        .andEq(ProjectContract::getContractName,projectContract.getContractName())
                        .orEq(ProjectContract::getContractNo,projectContract.getContractNo())).select();
        return 0 >= orgList.size();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id){
        ProjectContract projectContract = new ProjectContract();
        projectContract.setId(id);
        projectContract.setIsDelete(IsDeleteEnum.DELETE.getCode());
        return this.sqlManager.updateTemplateById(projectContract);
    }

    @Override
    public RtnInfo<ProjectContract> getInfo(Long id){
        ProjectContract projectContract = this.selectById(id);
        if (null == projectContract){
            return RtnInfo.error(RtnConstant.Code.PARAMS_REEOR,"未查到相关信息，请检查上送数据是否正确");
        } else {
            LambdaQuery<ProjectContractPayment> query = sqlManager.lambdaQuery(ProjectContractPayment.class);
            projectContract.setPaymentList(query.andEq(ProjectContractPayment::getBizId,id).select());
            return  RtnInfo.success(projectContract);
        }
    }

    @Override
    public Long getTotalNum(){
        LambdaQuery<ProjectContract> query = sqlManager.lambdaQuery(ProjectContract.class);
        return query.andEq(ProjectContract::getIsDelete,IsDeleteEnum.NOTDELETE.getCode()).count();
    }
}
